package com.yyk.yykywd.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.yyk.yykywd.R;
import com.yyk.yykywd.config.MyApplication;
import com.yyk.yykywd.listenter.ToolbarListenter;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by Administrator on 2018/9/14 0014.
 */

public abstract class BaseActivity extends AppCompatActivity {
    public static final String LAST_ACT = "LAST_ACT";
    public static final String BUNDLE = "TAG_BUNDLE";
    /**
     * 通用的ToolBar标题
     */
    private TextView commonTitleTv;

    private TextView commonTitleright;
    private TextView commonTitlerightIv;
    /**
     * 通用的ToolBar
     */
    private Toolbar commonTitleTb;
    /**
     * 下划线
     */
    private View viewE6_1;
    /**
     * 内容区域
     */
    private RelativeLayout content;

    private Unbinder bind;
    public Activity mActivity;


    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // TODO 设置状态栏和状态栏文字颜色(6.0)    简单的设置白色: 不好用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int color = statusBarColor();
            getWindow().setStatusBarColor(color);
            //状态栏为白色时，状态栏字体为灰色，其他都是默认颜色
            if (color == Color.WHITE) {
                setStatueTextColor(true);
            } else {
                setStatueTextColor(false);
            }
        }
         /*
         * 防止键盘挡住输入框 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
         * 希望动态调整高度 android:windowSoftInputMode="adjustResize"
         */
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_base);
        mActivity = this;
//        SoftHideKeyBoardUtil.assistActivity(mActivity);

        //当app关闭后关闭activity
        MyApplication.getInstance().addActivity(this);
        //设置竖屏
        initRequestedOrientation();
        //设置toolbar
        init();

        initView();
        setListener();
        initData();

//        CrashHandler.getIntanse().init(this);//初始化全局异常管理


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //        bind.unbind();
        //当一个activity finsh 后会调用 onDestroy   ，把已经销毁的activity从集合删除
        MyApplication.getInstance().removeActivity(this);
    }
    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */

    /**
     * Android状态栏一体化及状态栏文字颜色改变 - 开源首席情感分析师的个人空间 - 开源中国  https://my.oschina.net/u/197351/blog/856014
     * 侧滑栏效果所以设为全透明
     */
    public int statusBarColor() {
        return Color.WHITE;
    }

    /**
     * 设置状态栏颜色是否是灰色(默认白色和灰色)
     *
     * @param isGray
     */
    public void setStatueTextColor(boolean isGray) {
        if (isGray) {
            // 灰色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            // 白色
            getWindow().getDecorView().setSystemUiVisibility(0);
        }
    }

    private void init() {
        commonTitleTv = (TextView) findViewById(R.id.common_title_tv);
        commonTitleright = (TextView) findViewById(R.id.common_title_right_tv);
        commonTitlerightIv = (TextView) findViewById(R.id.common_title_right_iv);
        commonTitleTb = (Toolbar) findViewById(R.id.common_title_tb);
        content = (RelativeLayout) findViewById(R.id.content);
        viewE6_1 = (View) findViewById(R.id.view_e6_1);
        setSupportActionBar(commonTitleTb);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        setContentLayout(getLayoutId());
        bind = ButterKnife.bind(this);
        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        //        }


    }
    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */

    public abstract int getLayoutId();

    public abstract void initView();

    public abstract void initData();

    //钩子方法，它是一个空实现方法，子类可以视情况来决定是否要覆盖它
    protected void setListener() {
    }

    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */

    //TODO 设置全局toolbar  Android进阶---一个项目，一个Toolbar - 简书  https://www.jianshu.com/p/65cd2d4ad99a

    /**
     * 设置toolbar下面内容区域的内容
     *
     * @param layoutId
     */
    public void setContentLayout(@LayoutRes int layoutId) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(layoutId, null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        content.addView(contentView, params);
    }

    /**
     * 子类调用，重新设置Toolbar
     *
     * @param layout
     */
    public void setToolBar(int layout) {
        hidetoolBar();
        commonTitleTb = (Toolbar) content.findViewById(layout);
        setSupportActionBar(commonTitleTb);
        //设置actionBar的标题是否显示，对应ActionBar.DISPLAY_SHOW_TITLE。
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    /**
     * 隐藏ToolBar，通过setToolBar重新定制ToolBar
     */
    public void hidetoolBar() {
        commonTitleTb.setVisibility(View.GONE);
        viewE6_1.setVisibility(View.GONE);
    }


    /**
     * 设置左上角back按钮
     */
    public void setBackArrow() {
        final Drawable upArrow = getResources().getDrawable(R.mipmap.icon_fh);
        //给ToolBar设置左侧的图标
        getSupportActionBar().setHomeAsUpIndicator(upArrow);
        // 给左上角图标的左边加上一个返回的图标 。对应ActionBar.DISPLAY_HOME_AS_UP
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //设置返回按钮的点击事件
        commonTitleTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    /**
     * 设置左上角back按钮
     */
    public void setBackArrow(final ToolbarListenter listenter) {
        final Drawable upArrow = getResources().getDrawable(R.mipmap.icon_fh);
        //给ToolBar设置左侧的图标
        getSupportActionBar().setHomeAsUpIndicator(upArrow);
        // 给左上角图标的左边加上一个返回的图标 。对应ActionBar.DISPLAY_HOME_AS_UP
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //设置返回按钮的点击事件
        commonTitleTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listenter.onClickListenter();
            }
        });
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            commonTitleTv.setText(title);
        }
    }

    /**
     * 设置标题
     *
     * @param resId
     */
    public void setTitle(int resId) {
        commonTitleTv.setText(resId);
    }

    /**
     * 设置title右边文字
     *
     * @param text
     */
    public void setMainTitleRightText(String text, final ToolbarListenter listenter) {
        commonTitleright.setVisibility(View.VISIBLE);
        commonTitleright.setText(text);
        commonTitleright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listenter.onClickListenter();
            }
        });

    }

    /**
     * 设置title右边图片
     *
     * @param tupian
     */
    public void setMainTitleRightText(int tupian, final ToolbarListenter listenter) {
        commonTitlerightIv.setVisibility(View.VISIBLE);
        commonTitlerightIv.setBackgroundResource(tupian);
        commonTitlerightIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listenter.onClickListenter();
            }
        });

    }
    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */


    private void initRequestedOrientation() {
        //竖屏
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //禁止自动弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    }
    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */


    protected Bundle getBundle() {
        if (getIntent().hasExtra(BUNDLE)) {
            return getIntent().getBundleExtra(BUNDLE);
        }
        return null;
    }
    /**
     * Activity 跳转的操作   递归模式
     */
    /**
     * @see #startAct(Class, Bundle)
     */
    protected void startAct(Class<?> cls) {
        startAct(cls, null);
    }

    /**
     * @see #startAct(Intent, Class, Bundle)
     */
    protected void startAct(Class<?> cls, Bundle bundle) {
        startAct(null, cls, bundle);
    }

    /**
     * 启动Activity
     */
    protected void startAct(Intent intent, Class<?> cls, Bundle bundle) {
        if (intent == null)
            intent = new Intent();
        if (bundle != null)
            intent.putExtra(BUNDLE, bundle);
        intent.putExtra(LAST_ACT, this.getClass().getSimpleName());
        intent.setClass(this, cls);
        startActivity(intent);
    }

    /**
     * 不可以传值 可以控制当前界面是否finsh
     *
     * @param cls
     * @param isFinish
     */
    public void startAct(Class cls, boolean isFinish) {
        startAct(null, cls, null);
        if (isFinish) {
            finish();
        }
    }

    /**
     * 可以传值 并且可以控制当前界面是否finsh
     *
     * @param cls
     * @param isFinish
     * @param bundle
     */
    public void startAct(Class cls, boolean isFinish, Bundle bundle) {
        startAct(null, cls, bundle);
        if (isFinish) {
            finish();
        }
    }
    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */

    @Override
    public void onBackPressed() {
        this.finish();
        super.onBackPressed();

    }

    /*-----------------------------------------------------------------------------------------------------------------------------------------------------------  */

    /**
     * 点击页面其他地方取消EditText的焦点并且隐藏软键盘的方法 - CSDN博客  https://blog.csdn.net/u013273953/article/details/52921735
     */
    protected void initJianPan() {
        //可以点击 父容器 让软键盘消失掉
        content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (null != BaseActivity.this.getCurrentFocus()) {
                    /**
                     * 点击空白位置 隐藏软键盘
                     */
                    InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    return mInputMethodManager.hideSoftInputFromWindow(BaseActivity.this.getCurrentFocus().getWindowToken(), 0);
                }
                return false;
            }
        });
    }

    /**
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //Editext
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }

            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }

        return onTouchEvent(ev);
    }

    /**
     * 拦截事件
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }




}